const express = require('express');
const fs=require('fs');
const path=require('path');
const nunjucks = require('nunjucks');


/**
 * 复制模板文件到指定文件夹下
 * */

const copyFile = (formPath,toPath) => {
    if (fs.existsSync(toPath)) {
        console.log('路径存在，开始复制操作');
        fs.readdir(formPath, (err, data) => {
            data.forEach((e)=>{
                let _from=formPath+'/'+e;
                let _to=toPath+'/'+e;
                if(fs.statSync(_from).isDirectory()){
                    if(!fs.existsSync(_to))
                    {
                        fs.mkdirSync(_to)
                    }
                    copyFile(_from,_to);
                }else{
                    if(!fs.existsSync(_to))
                    {
                        fs.copyFileSync(_from,_to);
                    }
                    else{
                        console.log(`文件${toPath}已存在，跳过`)
                    }
                }
            })
        })
    }
};


class siteInit{
    constructor(app,path){
        this.app=app;
        this.path=path;
        this.init();
    }
    init(){
        let that=this;
        //静态资源目录
        this.app.use(express.static(that.path+'/src'));
        //配置模板引擎
        nunjucks.configure(that.path+'/html', {
            autoescape: true,
            express: that.app,
            noCache: process.env.NODE_ENV !== 'production'
        });

        this.countroler();
    }
    watch(){
        console.log('文件监控');
    }
    countroler(){
        let that=this;
        let filesList=fs.readdirSync(that.path+'/html');
        this.app.get('/page/:name',(req,res)=>{
            let pageName=req.params.name;
           if(filesList.indexOf(pageName)>-1)
           {
               res.render(that.path+'/html/'+pageName,{
                   fileName:pageName,
                   evn:'dev',
                   query:req.query
               })
           }
           else{
               res.render(that.path+'/html/system/404.html',{
                   fileName:pageName,
                   evn:'dev',
                   query:req.query
               })
           }
        });
    }
}

module.exports=siteInit;